package com.zys.el.user.service.Impl;


import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.zys.el.time.entity.AbsorbedDeal;
import com.zys.el.time.entity.Deal;
import com.zys.el.user.client.AbsorbedDealClient;
import com.zys.el.user.client.DealClient;
import com.zys.el.user.config.po.SynthesizeResult;
import com.zys.el.user.po.*;
import com.zys.el.user.service.*;
import com.zys.el.user.util.BaiduApi.TextSimilar;
import com.zys.el.user.util.TunxunApi.DiretSimilar;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Service
public class SynthesizeServiceImpl implements ISynthesizeService {

    @Autowired
    private ITargetService targetService;

    @Autowired
    private ITargetUserService targetUserService;
    @Autowired
    private IUserService userService;

    @Autowired
    private DealClient dealClient;
    @Autowired
    private AbsorbedDealClient absorbedDealClient;

    @Autowired
    private ITaskService taskService;
    @Autowired
    private IProssionService prossionService;

    //从大到小排序
    private class MyComparator implements Comparator<Map.Entry> {
        public int compare(Map.Entry o1, Map.Entry o2) {
            return ((Double) o2.getValue()).compareTo((Double) o1.getValue());
        }
    }

    private class MyComparator2 implements Comparator<Map.Entry> {
        public int compare(Map.Entry o1, Map.Entry o2) {
            return ((Long) o2.getValue()).compareTo((Long) o1.getValue());
        }
    }

    public List<Synthesize> getSynthesizeByReady() throws JsonProcessingException {
        List<Synthesize> result = new ArrayList<>();

        Map<Target, Double> targetDoubleMap = getTargetDoubleMap();

        List<Map.Entry<Target, Double>> entryList = new ArrayList<>(targetDoubleMap.entrySet());
        Collections.sort(entryList, new MyComparator());
        int position = 1;
        for (Map.Entry<Target, Double> entry : entryList) {
//            System.out.println(entry.getKey() + ", " + entry.getValue());
            Target key = entry.getKey();
            TargetUser targetUser = targetUserService.selectTargetByTargetId(key.getId());
            User byId = userService.getById(targetUser.getUserId());
            Synthesize sy = Synthesize.builder()
                    .user(byId)
                    .target(key)
                    .position(position)
                    .build();
            result.add(sy);
            position++;
//            System.out.println(sy);
        }
        return result;

    }

    /**
     * 用户所在省的学校排名,市排名，专业排名，院排名
     *
     * @return
     * @throws JsonProcessingException
     */
    @Override
    public SynthesizeResult getSynthesizeByForth(Long userId) throws JsonProcessingException {
        //userid
        //////////////////////////////////劣质代码/////////////////////////////////////////////////////
        /*Map<String, Long> schoolFaceCount = new HashMap<>();
        Map<String, List<Long>> schoolNameByUserId = prossionService.getSchoolNameByUserId(userId);
        for (String s : schoolNameByUserId.keySet()) {
            List<Long> professId = schoolNameByUserId.get(s);
            schoolFaceCount.put(s, 0L);
            Long count = 0L;
            for (Long pid : professId) {
                List<User> userIdByPID = userService.query().eq("profession_id_", pid).list();
                // TODO 根据时间过滤掉部分用户
                //////////
                if (userIdByPID == null || userIdByPID.size() == 0) continue;//如果该专业没人继续循环下一个专业

                for (User user : userIdByPID) {
                    TargetUser targetUser = targetUserService.selectTargetByUserId(user.getId());
                    if (targetUser == null) continue;//如果该用户没有目标就继续循环下一个用户
                    Target one = targetService.query().eq("id_", targetUser.getTargetId()).eq("delete_", 0).one();
                    if (one.getFanish() == null) one.setFanish(0);
                    if (one.getFanish() == 1) count++;
                }

            }
            Long newSum = schoolFaceCount.get(s);
            schoolFaceCount.put(s, count + newSum);
        }
        //保存学校列表的通过数
        Long position = 1L;
        Map<String, List<Long>> result = new HashMap<>();//0是数量，1名次
        List<Map.Entry<String, Long>> entryList = new ArrayList<>(schoolFaceCount.entrySet());
        Collections.sort(entryList, new MyComparator2());
        for (Map.Entry<String, Long> entry : entryList) {
            List<Long> dou = new ArrayList<>();
            dou.add(entry.getValue());
            dou.add(position);
            result.put(entry.getKey(), dou);
            position++;
        }

        System.out.println(result);
        return result;
        
         */

        /////////////////////////新思路/////////////////////////
        List<List<Synthesize>> result1 = new ArrayList<>(); // 存储学校分类学生排名
        List<Map<String, Long>> result2 = new ArrayList<>(); // 存储分区学生排名


        Prossion schoolOneNameByUserId = prossionService.getSchoolOneNameByUserId(userId);
        TargetUser targetUser = targetUserService.selectTargetByUserId(userId);
        Target userTarget = new Target();
        if (targetUser != null) {
            userTarget = targetService.getById(targetUser.getTargetId());
        } else {
            userTarget.setName("");
        }


        String province = schoolOneNameByUserId.getProvince();
        String prossionName = schoolOneNameByUserId.getProssionName();
        String prossionType = schoolOneNameByUserId.getProssionType();
        String school = schoolOneNameByUserId.getSchool();
        String city = schoolOneNameByUserId.getCity();
        List<Target> list = targetService.list();
        if (list == null || list.size() == 0) return null;
////////////////////////////////////////////////////各级对应大的通过数排名////////////////////////////////////////////////////////////////////////////////////////////
        Map<String, Long> schoolSynthesizeByProvince = new HashMap<>();//省内学校排名
        Map<String, Long> professionSynthesizeByProvince = new HashMap<>();//省内专业排名
        Map<String, Long> schoolSynthesizeByCity = new HashMap<>();//市内学校排名
        Map<String, Long> professionSynthesizeByCity = new HashMap<>();//市内专业排名
        Map<String, Long> professionTypeSynthesizeBySchool = new HashMap<>();//学校内院排名
        Map<String, Long> professionSynthesizeBySchool = new HashMap<>();//学校内专业排名
        Map<String, Long> professionSynthesizeByProfessionType = new HashMap<>();//院内专业排名

////////////////////////////////////////////////////用户对应的点赞数排名//////////////////////////////////////////////////////////////////////////////////////////////////
        Map<Synthesize, Long> studentsSynthesizeBySchool = new HashMap<>();//校内学生排名
        Map<Synthesize, Long> studentsSynthesizeByProfessionType = new HashMap<>();//院内学生排名
        Map<Synthesize, Long> studentsSynthesizeByProfession = new HashMap<>();//专业内学生排名

        for (Target target : list) {
            if (target.getName().equals(userTarget.getName()) == false) continue;
            Prossion professionByTargetId = prossionService.getProfessionByTargetId(target.getId());
//            System.out.println("professionByTargetId:" + professionByTargetId);
            if (professionByTargetId == null) continue;

            //省内学校排名
//            System.out.println(professionByTargetId.getProvince() + "=" + province);
            if (professionByTargetId.getProvince().equals(province)) {
//                System.out.println(professionByTargetId.getProvince() + "===" + province);
                if (schoolSynthesizeByProvince.get(professionByTargetId.getSchool()) != null) {
//                    System.out.println("=================================");
                    schoolSynthesizeByProvince.put(professionByTargetId.getSchool(), schoolSynthesizeByProvince.get(professionByTargetId.getSchool()) + 1);
                } else {
//                    System.out.println("===============+++++==============");
                    schoolSynthesizeByProvince.put(professionByTargetId.getSchool(), 1L);
                }
//                System.out.println("schoolSynthesizeByProvince:" + schoolSynthesizeByProvince);
            }


            //省内专业排名
            if (professionByTargetId.getProvince().equals(province)) {
                if (professionSynthesizeByProvince.get(professionByTargetId.getProssionName()) != null) {
                    professionSynthesizeByProvince.put(professionByTargetId.getProssionName(), professionSynthesizeByProvince.get(professionByTargetId.getProssionName()) + 1);
                } else {
                    professionSynthesizeByProvince.put(professionByTargetId.getProssionName(), 1L);
                }
            }

            //市内学校排名
            if (professionByTargetId.getCity().equals(city)) {
                if (schoolSynthesizeByCity.get(professionByTargetId.getSchool()) != null) {
                    schoolSynthesizeByCity.put(professionByTargetId.getSchool(), schoolSynthesizeByCity.get(professionByTargetId.getSchool()) + 1);
                } else {
                    schoolSynthesizeByCity.put(professionByTargetId.getSchool(), 1L);
                }
            }

            //市内专业排名
            if (professionByTargetId.getCity().equals(city)) {
                if (professionSynthesizeByCity.get(professionByTargetId.getProssionName()) != null) {
                    professionSynthesizeByCity.put(professionByTargetId.getProssionName(), professionSynthesizeByCity.get(professionByTargetId.getProssionName()) + 1);
                } else {
                    professionSynthesizeByCity.put(professionByTargetId.getProssionName(), 1L);
                }
            }

            //学校内院排名
            if (professionByTargetId.getSchool().equals(school)) {
                if (professionTypeSynthesizeBySchool.get(professionByTargetId.getProssionType()) != null) {
                    professionTypeSynthesizeBySchool.put(professionByTargetId.getProssionType(), professionTypeSynthesizeBySchool.get(professionByTargetId.getProssionType()) + 1);
                } else {
                    professionTypeSynthesizeBySchool.put(professionByTargetId.getProssionType(), 1L);
                }
            }

            //学校内专业排名
            if (professionByTargetId.getSchool().equals(school)) {
                if (professionSynthesizeBySchool.get(professionByTargetId.getProssionName()) != null) {
                    professionSynthesizeBySchool.put(professionByTargetId.getProssionName(), professionSynthesizeBySchool.get(professionByTargetId.getProssionName()) + 1);
                } else {
                    professionSynthesizeBySchool.put(professionByTargetId.getProssionName(), 1L);
                }
            }

            //院内专业排名
            if (professionByTargetId.getProssionType().equals(prossionType)) {
                if (professionSynthesizeByProfessionType.get(professionByTargetId.getProssionName()) != null) {
                    professionSynthesizeByProfessionType.put(professionByTargetId.getProssionName(), professionSynthesizeByProfessionType.get(professionByTargetId.getProssionName()) + 1);
                } else {
                    professionSynthesizeByProfessionType.put(professionByTargetId.getProssionName(), 1L);
                }
            }

            ///////////////////////////////////以上内容在前端只要求显示//////////////////////////////////
            //////////////////////////////////以下内容要求有用户信息////////////////////////////////////
            //校内学生排名
            if (professionByTargetId.getSchool().equals(school)) { //如果遍历目标是本学校的，按like排名
                TargetUser targetUserSchool = targetUserService.selectTargetByTargetId(target.getId());
                if (targetUserSchool == null) continue;//可能已经删除
                User user = userService.getById(targetUserSchool.getUserId());

                Synthesize synthesize = Synthesize.builder().user(user).position(0).target(target).build();

                if (studentsSynthesizeBySchool.get(synthesize) != null) { //
                    studentsSynthesizeBySchool.put(synthesize,
                            target.getLike() >= studentsSynthesizeBySchool.get(synthesize) ?
                                    target.getLike() :
                                    studentsSynthesizeBySchool.get(synthesize));
                } else { //即是当前用户目标又已完成是有多个的，因为用户可能删除了
                    studentsSynthesizeBySchool.put(synthesize, Long.parseLong(target.getLike().toString()));/////////可能出现强转错误
                }
            }


            //院内学生排名
            if (professionByTargetId.getProssionType().equals(prossionType)) { //如果遍历目标是本学校的，按like排名
                TargetUser targetUserSchool = targetUserService.selectTargetByTargetId(target.getId());
                if (targetUserSchool == null) continue;//可能已经删除
                User user = userService.getById(targetUserSchool.getUserId());
                if (user == null) continue;
                Synthesize synthesize = Synthesize.builder().user(user).position(0).target(target).build();//默认排名为0

                if (studentsSynthesizeByProfessionType.get(synthesize) != null) { //
                    studentsSynthesizeByProfessionType.put(synthesize,
                            target.getLike() >= studentsSynthesizeByProfessionType.get(synthesize) ?
                                    target.getLike() :
                                    studentsSynthesizeByProfessionType.get(synthesize));
                } else { //即是当前用户目标又已完成是有多个的，因为用户可能删除了
                    studentsSynthesizeByProfessionType.put(synthesize, Long.parseLong(target.getLike().toString()));/////////可能出现强转错误
                }
            }

            //专业内学生排名
            if (professionByTargetId.getProssionName().equals(prossionName)) { //如果遍历目标是本学校的，按like排名
                TargetUser targetUserSchool = targetUserService.selectTargetByTargetId(target.getId());
                if (targetUserSchool == null) continue;//可能已经删除
                User user = userService.getById(targetUserSchool.getUserId());
                if (user == null) continue;
                Synthesize synthesize = Synthesize.builder().user(user).position(0).target(target).build();//默认排名为0

                if (studentsSynthesizeByProfession.get(synthesize) != null) { //
                    studentsSynthesizeByProfession.put(synthesize,
                            target.getLike() >= studentsSynthesizeByProfession.get(synthesize) ?
                                    target.getLike() :
                                    studentsSynthesizeByProfession.get(synthesize));
                } else { //即是当前用户目标又已完成是有多个的，因为用户可能删除了
                    studentsSynthesizeByProfession.put(synthesize, Long.parseLong(target.getLike().toString()));/////////可能出现强转错误
                }
            }
        }

//        System.out.println("schoolSynthesizeByProvince: " + schoolSynthesizeByProvince);
//        System.out.println("professionSynthesizeByProvince: " + professionSynthesizeByProvince);
//        System.out.println("schoolSynthesizeByCity: " + schoolSynthesizeByCity);
//        System.out.println("professionSynthesizeByCity: " + professionSynthesizeByCity);
//        System.out.println("professionTypeSynthesizeBySchoolPosition: " + professionTypeSynthesizeBySchool);
//        System.out.println("professionSynthesizeBySchool: " + professionSynthesizeBySchool);
//        System.out.println("professionSynthesizeByProfessionType: " + professionSynthesizeByProfessionType);

        // 存储排名的数据结构
        Map<String, Long> schoolSynthesizeByProvincePosition = new HashMap<>();//省内学校排名
        Map<String, Long> professionSynthesizeByProvincePosition = new HashMap<>();//省内专业排名
        Map<String, Long> schoolSynthesizeByCityPosition = new HashMap<>();//市内学校排名
        Map<String, Long> professionSynthesizeByCityPosition = new HashMap<>();//市内专业排名
        Map<String, Long> professionTypeSynthesizeBySchoolPosition = new HashMap<>();//学校内院排名
        Map<String, Long> professionSynthesizeBySchoolPosition = new HashMap<>();//学校内专业排名
        Map<String, Long> professionSynthesizeByProfessionTypePosition = new HashMap<>();//院内专业排名

        Long position = 0L;
        List<Map.Entry<String, Long>> schoolSynthesizeByProvinceEntryList = new ArrayList<>(schoolSynthesizeByProvince.entrySet());
        Collections.sort(schoolSynthesizeByProvinceEntryList, new MyComparator2());
        for (Map.Entry<String, Long> stringLongEntry : schoolSynthesizeByProvinceEntryList) {
            schoolSynthesizeByProvincePosition.put(stringLongEntry.getKey(), ++position);
        }
        result2.add(schoolSynthesizeByProvincePosition);

        position = 0L;
        List<Map.Entry<String, Long>> professionSynthesizeByProvinceEntryList = new ArrayList<>(professionSynthesizeByProvince.entrySet());
        Collections.sort(professionSynthesizeByProvinceEntryList, new MyComparator2());
        for (Map.Entry<String, Long> stringLongEntry : professionSynthesizeByProvinceEntryList) {
            professionSynthesizeByProvincePosition.put(stringLongEntry.getKey(), ++position);
        }
        result2.add(professionSynthesizeByProvincePosition);

        position = 0L;
        List<Map.Entry<String, Long>> schoolSynthesizeByCityEntryList = new ArrayList<>(schoolSynthesizeByCity.entrySet());
        Collections.sort(schoolSynthesizeByCityEntryList, new MyComparator2());
        for (Map.Entry<String, Long> stringLongEntry : schoolSynthesizeByCityEntryList) {
            schoolSynthesizeByCityPosition.put(stringLongEntry.getKey(), ++position);
        }
        result2.add(schoolSynthesizeByCityPosition);

        position = 0L;
        List<Map.Entry<String, Long>> professionSynthesizeByCityEntryList = new ArrayList<>(professionSynthesizeByCity.entrySet());
        Collections.sort(professionSynthesizeByCityEntryList, new MyComparator2());
        for (Map.Entry<String, Long> stringLongEntry : professionSynthesizeByCityEntryList) {
            professionSynthesizeByCityPosition.put(stringLongEntry.getKey(), ++position);
        }
        result2.add(professionSynthesizeByCityPosition);

        position = 0L;
        List<Map.Entry<String, Long>> professionTypeSynthesizeBySchoolEntryList = new ArrayList<>(professionTypeSynthesizeBySchool.entrySet());
        Collections.sort(professionTypeSynthesizeBySchoolEntryList, new MyComparator2());
        for (Map.Entry<String, Long> stringLongEntry : professionTypeSynthesizeBySchoolEntryList) {
            professionTypeSynthesizeBySchoolPosition.put(stringLongEntry.getKey(), ++position);
        }
        result2.add(professionTypeSynthesizeBySchoolPosition);

        position = 0L;
        List<Map.Entry<String, Long>> professionSynthesizeBySchoolEntryList = new ArrayList<>(professionSynthesizeBySchool.entrySet());
        Collections.sort(professionSynthesizeBySchoolEntryList, new MyComparator2());
        for (Map.Entry<String, Long> stringLongEntry : professionSynthesizeBySchoolEntryList) {
            professionSynthesizeBySchoolPosition.put(stringLongEntry.getKey(), ++position);
        }
        result2.add(professionSynthesizeBySchoolPosition);

        position = 0L;
        List<Map.Entry<String, Long>> professionSynthesizeByProfessionTypeEntryList = new ArrayList<>(professionSynthesizeByProfessionType.entrySet());
        Collections.sort(professionSynthesizeByProfessionTypeEntryList, new MyComparator2());
        for (Map.Entry<String, Long> stringLongEntry : professionSynthesizeByProfessionTypeEntryList) {
            professionSynthesizeByProfessionTypePosition.put(stringLongEntry.getKey(), ++position);
        }
        result2.add(professionSynthesizeByProfessionTypePosition);
//        System.out.println("[][][][]][][][][[][][]][][][][][][][][][]");
//        System.out.println("schoolSynthesizeByProvince: " + schoolSynthesizeByProvincePosition);
//        System.out.println("professionSynthesizeByProvince: " + professionSynthesizeByProvincePosition);
//        System.out.println("schoolSynthesizeByCity: " + schoolSynthesizeByCityPosition);
//        System.out.println("professionSynthesizeByCity: " + professionSynthesizeByCityPosition);
//        System.out.println("professionTypeSynthesizeBySchoolPosition: " + professionTypeSynthesizeBySchoolPosition);
//        System.out.println("professionSynthesizeBySchool: " + professionSynthesizeBySchoolPosition);
//        System.out.println("professionSynthesizeByProfessionType: " + professionSynthesizeByProfessionTypePosition);
//        System.out.println("[][][][]][][][][[][][]][][][][][][][][][]");
/////////////////////////////////////////////////////////学生排序/////////////////////////////////////////////////////////////////////////////////

        List<Map.Entry<Synthesize, Long>> studentsSynthesizeBySchoolEntryList = new ArrayList<>(studentsSynthesizeBySchool.entrySet());
        Collections.sort(studentsSynthesizeBySchoolEntryList, new MyComparator2());
        List<Map.Entry<Synthesize, Long>> studentsSynthesizeByProfessionTypeEntryList = new ArrayList<>(studentsSynthesizeByProfessionType.entrySet());
        Collections.sort(studentsSynthesizeByProfessionTypeEntryList, new MyComparator2());
        List<Map.Entry<Synthesize, Long>> studentsSynthesizeByProfessionEntryList = new ArrayList<>(studentsSynthesizeByProfession.entrySet());
        Collections.sort(studentsSynthesizeByProfessionEntryList, new MyComparator2());

        List<Synthesize> studentsSynthesizeBySchoolResult = new ArrayList<>();
        int count = 1;
        for (Map.Entry<Synthesize, Long> synthesizeLongEntry : studentsSynthesizeBySchoolEntryList) {
            Synthesize key = synthesizeLongEntry.getKey();
            key.setPosition(count);
            studentsSynthesizeBySchoolResult.add(key);
            count++;
        }
        result1.add(studentsSynthesizeBySchoolResult);

        List<Synthesize> studentsSynthesizeByProfessionTypeResult = new ArrayList<>();
        count = 1;
        for (Map.Entry<Synthesize, Long> synthesizeLongEntry : studentsSynthesizeByProfessionTypeEntryList) {
            Synthesize key = synthesizeLongEntry.getKey();
            key.setPosition(count);
            studentsSynthesizeByProfessionTypeResult.add(key);
            count++;
        }
        result1.add(studentsSynthesizeByProfessionTypeResult);

        List<Synthesize> studentsSynthesizeByProfessionResult = new ArrayList<>();
        count = 1;
        for (Map.Entry<Synthesize, Long> synthesizeLongEntry : studentsSynthesizeByProfessionEntryList) {
            Synthesize key = synthesizeLongEntry.getKey();
            key.setPosition(count);
            studentsSynthesizeByProfessionResult.add(key);
            count++;
        }
        result1.add(studentsSynthesizeByProfessionResult);

        // 封装结果
        SynthesizeResult result = new SynthesizeResult();
        result.setPlacesSize(result2);
        result.setSchoolSize(result1);
        return result;
    }


    //n个目标，每个目标有一个用户，一个用户对应m个待办，一个目标对应
    //public void getSynthesize() throws JsonProcessingException {
    private Map<Target, Double> getTargetDoubleMap() {
        Map<Target, Double> targetDoubleMap = new HashMap<>();
        //查询所有目标得到目标列表
        List<Target> list = targetService.selectListNoDelete();//error
        if (list == null || list.size() == 0) return targetDoubleMap;
        List<Deal> dealList = new ArrayList<>();
        List<Task> taskByTargetId = new ArrayList<>();
        Double hope = 0D;
        //对每个目标查询其用户（根据目标查询中间表id，中间表id查询用户）

        for (Target target : list) {
            TargetUser targetUser = targetUserService.selectTargetByTargetId(target.getId());
            Map<Task, Double> dealTaskMap = new HashMap<>();//存着每一个任务的执行概率=执行总时间/任务时间,注意：这只是一个目标的
            if (targetUser == null) continue;
            User user = userService.getById(targetUser.getUserId());
            if (user == null) continue;
            //根据用户id查询待办组
            dealList = dealClient.list(user.getId().toString()).getData();

            if (dealList == null || dealList.size() == 0) continue;
            //对各个目标查询其任务组
            taskByTargetId = taskService.getTaskByTargetId(target.getId());

            if (dealList == null || taskByTargetId == null || dealList.size() == 0 || taskByTargetId.size() == 0)
                continue;
            //判断词语相似是否有结果
            //没有结果就判断文本相似度，大于0就为可以，等于0就是不可以

            for (Task task : taskByTargetId) {
                for (Deal deal : dealList) {
                    String dealName = deal.getTitle();
                    String taskName = task.getName();

                    DiretSimilar diretSimilar = new DiretSimilar();
                    String result = diretSimilar.result(taskName, dealName);
                    if (result != "") {
                        String Similarity = JSONObject.parseObject(result).get("Similarity").toString();
                        if (Double.parseDouble(Similarity) <= 0.2) continue;//不相关就看下一个待办
                        //大于0.2为相关
                        dealTaskMap = MapSum(task, deal, dealTaskMap);
                    } else {//如果api接口词库中没有就进行文本相似匹配
                        ////////////////////////////此段代码应用了百度云，结果还是可能为空///////////////////////////////////////////
//                        TextSimilar textSimilar = new TextSimilar();
//
//                        try {
//                            String result2 = textSimilar.result(taskName, dealName);
//                            if (result2 == null) continue;
//                            String score = JSONObject.parseObject(result2).get("score").toString();/////////error
//                            if (score != null) {
//                                if (Double.parseDouble(score) > 0.4) {
//                                    dealTaskMap = MapSum(task, deal, dealTaskMap);
//                                } else {
//                                    continue;
//                                }
//                            } else {
//                                System.out.println("识别错误");
//                                ///////////////////////////////////此处任务对应待办还是识别错误，TODO进一步模糊识别////////////////////////////////////////
//                                continue;
//                            }
//                            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                        } catch (IOException e) {
//                            throw new RuntimeException(e);
//                        }
                        continue;
                    }
                }
            }
            hope = 0D;
            //得到一组任务的期望
            hope = HopeTask(taskByTargetId);
            //计算实际执行
            List<Double> dealDouble = new ArrayList<>();
            for (Task task : dealTaskMap.keySet()) {
                dealDouble.add(dealTaskMap.get(task));
            }
            Double current = HopeDeal(dealDouble);
            //完成度
            if (hope != 0 && current != 0) {
                Double effect = ((new BigDecimal(current.toString())).divide(new BigDecimal(hope.toString()), 5, RoundingMode.HALF_UP)).doubleValue();
                target.setUserId(user.getId());
                targetDoubleMap.put(target, effect);//得到各个目标的效率
            } else {
                targetDoubleMap.put(target, 0D);
            }
        }

        //返回各个目标对应的执行度
        return targetDoubleMap;
    }


    //计算一组任务的期望
    private Double HopeTask(List<Task> tasks) {
        if (tasks == null) {
            return 0D;
        }
        BigDecimal sumTime = new BigDecimal(0);
        for (Task task : tasks) {
            BigDecimal bigDecimal = new BigDecimal((task.getTimeLength() != null) ? task.getTimeLength() : "0");
            sumTime = sumTime.add(bigDecimal);
        }//计算总值
        BigDecimal sumX = new BigDecimal(0);
        BigDecimal sumP = new BigDecimal(0);
        for (Task task : tasks) {
            BigDecimal bigDecimal = new BigDecimal((task.getTimeLength() != null) ? task.getTimeLength() : "0");
            BigDecimal divide = bigDecimal.divide((sumTime.doubleValue() == 0D ? new BigDecimal(1) : sumTime), 5, BigDecimal.ROUND_HALF_UP);//计算各个任务的占比
            BigDecimal multiply = divide.multiply(new BigDecimal((task.getTimeLength() != null) ? task.getTimeLength() : "0"));//各个任务占比乘任务系数
            sumP = sumP.add(multiply);//相加各个任务期望
        }
//        BigDecimal divide = sumP.divide(new BigDecimal(tasks.size()), 5, BigDecimal.ROUND_HALF_UP);//总任务期望除任务个数地道道总期望
        return sumP.doubleValue();
    }

    //计算一组任务的期望
    private Double HopeDeal(List<Double> tasks) {

        if (tasks == null || tasks.size() == 0) return 0D;
        BigDecimal sumTime = new BigDecimal(1);
        for (Double task : tasks) {
            sumTime = sumTime.add(new BigDecimal(task.toString()));
        }//计算总值
        BigDecimal sumX = new BigDecimal(1);
        BigDecimal sumP = new BigDecimal(1);
        for (Double task : tasks) {
            BigDecimal bigDecimal = new BigDecimal(task.toString());
            BigDecimal divide = bigDecimal.divide(sumTime, 5, BigDecimal.ROUND_HALF_UP);//计算各个任务的占比
            BigDecimal multiply = divide.multiply(new BigDecimal(task.toString()));//各个任务占比乘任务系数
            sumP = sumP.add(multiply);//相加各个任务期望
        }
//        BigDecimal divide = sumP.divide(new BigDecimal(tasks.size()), 5, BigDecimal.ROUND_HALF_UP);//总任务期望除任务个数地道道总期望
        return sumP.doubleValue();
    }

    //一个待办执行时间在一个任务中的增加
    private Map<Task, Double> MapSum(Task task, Deal deal, Map<Task, Double> taskDoubleMap) {
        //////deal  dealTaskMap
        //根据deal的id查其花销时间
        List<AbsorbedDeal> abDealByDealId = absorbedDealClient.getAbDealByDealId(deal.getDealId().toString().trim());
        if (abDealByDealId == null || abDealByDealId.size() == 0) return taskDoubleMap;

        //如果以一个待办的没有执行时间，那么为0
        int DealSum = 0;
        for (AbsorbedDeal absorbedDeal : abDealByDealId) {
            String[] split = absorbedDeal.getAbsorbedDuration().split(":");
            int temp = (Integer.parseInt(split[0]) * 3600 +
                    Integer.parseInt(split[1]) * 60 +
                    Integer.parseInt(split[2]));
            DealSum += temp;
        }
        BigDecimal BigDeal = new BigDecimal(DealSum);
        //double taskResult = divide.doubleValue();//一个待办对应适合的任务的执行时间

        //多个待办对应一个任务，此处只是一个任务，所以应该在对应的map的key对应的值上相加

        //得到此任务的此时的执行时间
        Double taskKey = taskDoubleMap.get(task);
        if (taskKey == null) taskKey = 0D;
        if (taskKey != null) {//不是第一次插入就在基础上加
            BigDecimal taskKeyBig = new BigDecimal(taskKey.toString());
            BigDecimal taskKeyValue = taskKeyBig.add(BigDeal);

            taskDoubleMap.put(task, taskKeyValue.doubleValue());//更新此task的执行时间
        } else {//否则就插入
            taskDoubleMap.put(task, taskKey);
        }
//        System.out.println("taskDoubleMap" + taskDoubleMap);
        return taskDoubleMap;
    }
    

}


